package com.csii.activiti.server.core.listener;

import com.csii.activiti.server.core.constant.ActFlowAutoApprovalConstant;
import com.csii.activiti.server.core.entity.ActBackTask;
import com.csii.activiti.server.core.entity.ActCompleteTask;
import com.csii.activiti.server.core.entity.ActFlowAutoApprovalConfiguration;
import com.csii.activiti.server.core.entity.ActFlowNode;
import com.csii.activiti.server.core.mapper.ActFlowNodeMapper;
import com.csii.activiti.server.core.service.FlowOperationService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.List;

@Component
public class FlowAutoApprovalDelegate implements JavaDelegate, Serializable {

    @Autowired
    private TaskService taskService;

    @Autowired
    private ActFlowNodeMapper actFlowNodeMapper;

    @Autowired
    private FlowOperationService flowOperationService;


    @Override
    public void execute(DelegateExecution execution) {
        if (execution instanceof ExecutionEntityImpl) {
            ExecutionEntityImpl executionEntity = (ExecutionEntityImpl) execution;
            String processInstanceId = executionEntity.getProcessInstanceId();
            List<Task> taskList = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
            Task oneTask = taskList.get(0);
            ActFlowNode actFlowNode = actFlowNodeMapper.selectById(oneTask.getTaskDefinitionKey()).transitionActFlowNode();
            ActFlowAutoApprovalConfiguration flowAutoApprovalConfiguration =actFlowNode.getConfigurationItem().getFlowAutoApprovalConfiguration();

            if (ActFlowAutoApprovalConstant.AUTO_PASS.equals(flowAutoApprovalConfiguration.getApprovalType())) {
                for (Task task : taskList) {
                    flowOperationService.completeTask(new ActCompleteTask(task.getId()," 当前审批环节已经配置了到期自动审批，到期后会自动审批通过"));
                }
            }else if(ActFlowAutoApprovalConstant.AUTO_REFUSE.equals(flowAutoApprovalConfiguration.getApprovalType())){
                for (Task task : taskList) {
                    flowOperationService.backTask(new ActBackTask(task.getId()," 当前审批环节已经配置了到期自动审批，到期后会自动审批拒绝"));
                }
            }

        }
    }
}
